import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store/index.js'
import router from '@/router/index.js'

const _axios = axios.create({
  baseURL: process.env.VUE_APP_BASE_API
})
// 请求ing的数组
let cancelArr = []
// 导出一个取消所有请求的方法,(用于路由跳转时触发)
export function cancelAll() {
  cancelArr.forEach((item) => {
    item.cancel()
  })
  cancelArr = []
}
// 请求拦截
_axios.interceptors.request.use(
  (config) => {
    // 先取消上一个未完成的地址和方法相同的请求
    cancelArr = cancelArr.filter((item) => {
      if (item.url === config.url && item.method === config.method) {
        item.cancel()
        return false
      } else {
        return true
      }
    })
    // 记录每一次请求,并添加取消的方法
    config.cancelToken = new axios.CancelToken((cancel) => {
      cancelArr.push({
        url: config.url,
        method: config.method,
        cancel: cancel
      })
    })

    if (store.state.user.token) {
      config.headers.Authorization = `Bearer ${store.state.user.token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)
// 响应拦截
_axios.interceptors.response.use(
  (res) => {
    if (res.data.success) {
      return res.data
    } else {
      Message.error(res.data.message)
      return Promise.reject(res.data.message)
    }
  },
  (error) => {
    console.log([error])
    if (error.response.status === 401) {
      store.commit('user/logout')
      router.push('/login?redirect' + location.href.split('#')[1])
    }
    return Promise.reject(error)
  }
)
export default _axios
